import Taro, { Component } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import Banner from '../../../static/home/banner.png';
import './index.scss';
import { orderDetail, cancleList, deleteOrder, calOrder, deliveryOrder, orderCheck, testPay, orderPay } from '../../../services/order';
import { ORDER_STATUS } from '../../../utils/config';
import { timeFormat, fullImgUrl, secondToDate } from '../../../utils/utils';
import NavigationBar from '../../../components/navigationBar/index';
import UpdateModal from '../../../components/update-modal/index';
export default class Index extends Component {

  config = {
    navigationBarTitleText: '订单详情'
  }

  state = {
    spareTime: null, // 订单自动取消的剩余时间
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    setting: Taro.getStorageSync('setting'),
    orderInfo: null,
    isShowCancleWrapper: false,
    cancleReasonList: null,
    isShowUpdateModal: false,
  }

  componentWillMount() {
    this.init();
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() {
    this.init();
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  init() {
    orderDetail({
      order_info_id: this.$router.params.id
    }).then(res => {
      res.create_time = timeFormat(res.create_time)
      res.has_order_goods_sku[0].cover = fullImgUrl(res.has_order_goods_sku[0].cover)
      this.setState({
        orderInfo: res
      }, () => {
        if (this.state.orderInfo.order_status === 0) {
          this.setState({
            spareTime: secondToDate(this.state.orderInfo.expire_time - parseInt(new Date().getTime() / 1000, 10))
          })
          let intervalId = setInterval(() => {
            if (this.state.orderInfo.expire_time - parseInt(new Date().getTime() / 1000, 10) <= 0) {
              clearInterval(intervalId)
              let temp = this.state.orderInfo
              temp.order_status = 1
              this.setState({
                orderInfo: temp
              })
            }
            this.setState({
              spareTime: secondToDate(this.state.orderInfo.expire_time - parseInt(new Date().getTime() / 1000, 10))
            })
          }, 1000)
        }
      })
    })
  }

  delOrder(orderId) {
    let self = this;
    Taro.showModal({
      title: '提示',
      content: '删除后不可恢复,你确定要删除吗？',
      success: function (res) {
        if (res.confirm) {
          deleteOrder({
            order_info_id: orderId
          }).then(res => {
            Taro.navigateBack();
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  }

  chooseReason(item, index) {
    console.log(item, index);
    let temp = this.state.cancleReasonList;
    temp.forEach(item => {
      item.isChecked = false;
    });
    temp[index].isChecked = true;
    this.setState({
      cancleReasonList: temp
    }, () => {
      calOrder({
        order_info_id: this.$router.params.id,
        cancel_id: temp[index].id,
      }).then(res => {
        this.init();
        this.setState({
          isShowCancleWrapper: false,
        })
      })
    });
  }

  closeCancleWrapper() {
    this.setState({
      isShowCancleWrapper: false
    });
  }

  cancleOrder(orderId) {
    if (!this.state.cancleReasonList) {
      cancleList().then(res => {
        console.log(res)
        res.forEach(item => {
          item.isChecked = false;
        })
        this.setState({
          cancleReasonList: res,
          isShowCancleWrapper: true
        })
      })
    } else {
      this.setState({
        isShowCancleWrapper: true
      })
    }
  }

  applyInvoice(orderId) {
    console.log(orderId, '申请发票');
    Taro.navigateTo({
      url: `/subPackageWork/pages/apply-invoice/index?id=${orderId}`
    });
  }

  checkOrder(orderId) {
    orderCheck({
      order_info_id: orderId
    }).then(res => {
      this.init();
    })
  }

  goPay(orderId) {
    // testPay({
    //   order_id: orderId,
    //   pay_type: 1,
    //   pay_platform: 1
    // }).then(res => {
    //   this.init();
    // })
    let self = this
    orderPay({
      order_id: orderId,
      // pay_type: 1,
      pay_type: 3,
      pay_platform: 1
    }).then(data => {
      Taro.requestPayment({
        // ...data,
        ...(JSON.parse(data.payload).metadata),
        success() {
          console.log('ok')
          self.init()
        },
        fail() {
          console.log('not ok')
        }
      })
    })
  }

  checkExpress(order) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/express-status/index?id=${order.order_info_id}`
    })
  }

  update() {
    this.setState({
      isShowUpdateModal: true,
    })
  }

  updateAddress(order) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/my-address/index?orderId=${order.order_info_id}`
    });
  }

  cancelModal() {
    this.setState({
      isShowUpdateModal: false,
    })
  }

  render() {
    const { isShowUpdateModal, cancleReasonList, orderInfo, setting, navigationBarHeight, spareTime } = this.state;
    return (
      orderInfo ? <View className="order-detail" style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="订单详情" />
        {isShowCancleWrapper && <View className="mask" onClick={this.hideMask}></View>}
        {isShowCancleWrapper && <View className="cancle-wrapper">
          <View className="title">
            <View className="left">请选择取消订单原因</View>
            <View className="close" onClick={this.closeCancleWrapper}>x</View>
          </View>
          <View className="tips">温馨提示: 订单一旦取消,积分将不予返还！</View>
          <View className="cancle-reason-list">
            {
              cancleReasonList.map((item, index) => {
                return <View onClick={this.chooseReason.bind(this, item, index)} className="item" key={index}>
                  <View className={item.isChecked ? 'active circle' : 'circle'}></View>
                  <View className="reason">{item.name}</View>
                </View>
              })
            }
          </View>
        </View>}
        <View className="order-status">
          <View className="top">
            <View>{ORDER_STATUS[orderInfo.order_status]}</View>
            {orderInfo.order_status === 0 && <View>¥ {orderInfo.goods_amount}</View>}
          </View>
          <View className="bottom">
            {orderInfo.order_status === 0 && <View>剩余{spareTime}系统将自动取消订单</View>}
            {/* <View>应付金额</View> */}
            {orderInfo.order_status !== 0 && <View>客服联系电话:  {setting.mobile}</View>}
          </View>
        </View>
        <View className="user-wrapper">
          <View className="user-info">
            <View className="username">{orderInfo.receiver}</View>
            <View className="tel">{orderInfo.mobile}</View>
          </View>
          <View className="address-info">
            {orderInfo.province_name}{orderInfo.city_name}{orderInfo.region_name} {orderInfo.address}
          </View>
        </View>
        <View className="goods-wrapper">
          <View className="top">
            <View className="goods-number">共 {orderInfo.has_order_goods_sku.length} 件商品</View>
            {orderInfo.delivery_time && <View className="time">{orderInfo.delivery_time}发货</View>}
          </View>
          <View className="goods-detail">
            <Image className="goods-image" src={orderInfo.has_order_goods_sku[0].cover} alt="商品图" />
            <View className="goods-info">
              <View className="goods-name">{orderInfo.has_order_goods_sku[0].goods_name}</View>
              <View className="goods-desc">{orderInfo.has_order_goods_sku[0].has_order_goods_attr.map(attr => attr.goods_sku_attr_name + ' ')}</View>
              <View className="goods-specification">
                <View className="goods-number">数量: {orderInfo.has_order_goods_sku[0].num}</View>
                <View className="goods-price">¥ {orderInfo.goods_amount}</View>
              </View>
            </View>
          </View>
          <View className="should-pay">
            <View className="text">运费</View>
            <View className="money">¥ {orderInfo.shipping_fee}</View>
          </View>
          <View className="should-pay">
            <View className="text">优惠金额</View>
            <View className="money">¥ {orderInfo.act_discount}</View>
          </View>
          <View className="should-pay">
            <View className="text">会员优惠</View>
            <View className="money">¥ {orderInfo.member_amount}</View>
          </View>
          <View className="should-pay">
            <View className="text">应付金额</View>
            <View className="money">¥{orderInfo.paid_amount}</View>
          </View>
        </View>
        <View className="order-info">
          <View className="content">订单编号   {orderInfo.order_sn}</View>
          <View className="content">下单时间   {orderInfo.create_time}</View>
        </View>
        <View className="order-opt">
          {orderInfo.order_status === 0 && <View onClick={this.goPay.bind(this, orderInfo.order_info_id)} className="opt-btn to-pay">去支付</View>}
          {orderInfo.order_status === 3 && <View onClick={this.checkOrder.bind(this, orderInfo.order_info_id)} className="opt-btn check-order">确认收货</View>}
          {orderInfo.order_status === 3 && <View onClick={() => { this.checkExpress(orderInfo) }} className="opt-btn look-logistics">查看物流</View>}
          {orderInfo.order_status === 2 && !orderInfo.is_update_delivery_time && <View onClick={this.update.bind(this, orderInfo)} className="opt-btn update">修改时间</View>}
          {orderInfo.order_status === 2 && !orderInfo.is_update_address && <View onClick={this.updateAddress.bind(this, orderInfo)} className="opt-btn update">修改地址</View>}
          {(orderInfo.order_status === 3 || orderInfo.order_status === 4 || orderInfo.order_status === 2) && !orderInfo.is_receipt && <View className="opt-btn request-invoice" onClick={this.applyInvoice.bind(this, orderInfo.order_info_id)}>申请发票</View>}
          {(orderInfo.order_status === 1 || orderInfo.order_status === 4) && <View className="opt-btn del-order" onClick={this.delOrder.bind(this, orderInfo.order_info_id)}>删除订单</View>}
          {orderInfo.order_status === 0 && <View className="opt-btn del-order" onClick={this.cancleOrder.bind(this, orderInfo.order_info_id)}>取消订单</View>}
        </View>
        {isShowUpdateModal && <UpdateModal notifyParentRefresh={this.init.bind(this)} orderInfo={orderInfo} cancel={this.cancelModal.bind(this)} />}
      </View> : <View></View>
    );
  }
}
